Think back to the train.
Lets imagine a conductor who can only enter the train through the engine, and
can walk through the train down the line as long as the connector connects to
another car. This is how the program will traverse the linked list. The conductor
will be a pointer to node, and it will first point to root, and then, if the
root's pointer to the next node is pointing to something, the
"conductor" (not a technical term) will be set to point to the next
node. In this fashion, the list can be traversed. Now, as long as there is a
pointer to something, the traversal will continue. Once it reaches a NULL
pointer, meaning there are no more nodes (train cars) then it will be at the
end of the list, and a new node can subsequently be added if so
desired. COMMENT TO THE CODE: That is the basic code for traversing a list. The if statement ensures that there is something to begin with (a first node). In the example it will always be so, but if it was changed, it might not be true. If the if statement is true, then it is okay to try and access the node pointed to by conductor. The while loop will continue as long as there is another pointer in the next. The conductor simply moves along. It changes what it points to by getting the address of conductor->next. |